#include <sys/timeb.h> 
#include<stdio.h>
#include<iostream>
#include<fstream>
#include<sstream>
#include<math.h>

using namespace std;

struct timeb tstart;
struct timeb tstop;

clock_t cstart;
clock_t cstop;

float ttime;
float gtime; // time function granularity
float acc = 1000; //min number of grain times for a valid test
float mtime; // min time for test to run = acc*gtime
float cpu;
long tlength; // test iterations

void tGrain(int glength) {
  for (int j=0; j<glength; j++) {
    sin(0.1*M_PI*j);
  }
}

void tStart() {

  ftime(&tstart);
  cstart = clock();  
  
}

void tStop() {
  cstop = clock();
  ftime(&tstop);
  ttime = (float)(tstop.time-tstart.time)+((float)(tstop.millitm-tstart.millitm))/1000.0f;
  float ctime = (1.0*(cstop-cstart))/CLOCKS_PER_SEC;
  if ((!(ttime == 0.0))&&(ctime<ttime)) {
    cpu = ctime/ttime;
  } else {
    cpu = 1.0;
  }
}

void tReset() {
  ttime = 0.0;
  cpu = 1.0;
}

void getGrain() {
  // Probe timing functions for granularity
  int glength = 1;
  tStart();
  tStop();
  while (ttime == 0.0) {
    glength = 2*glength;
    tStart();
    tGrain(glength);
    tStop();
  }
  gtime = ttime;
//  cout << "Granularity is " << gtime << " sec" << endl;
  mtime = acc*gtime;
//  cout << "Minimum test length set to " << mtime << " sec" <<endl;
}
